<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="登录账户" size="small">
            <el-input v-model="searchForm.userName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="professions">
          <el-form-item label="所属团队" size="small">
            <el-select v-model="searchForm.teamId" placeholder="请选择所属团队">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in teams"
                :key="item.teamId"
                :label="item.teamName"
                :value="item.teamId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="100px">
          <el-form-item prop="userName" label="登录账户" size="small">
            <el-input v-model="teamRow.userName"></el-input>
          </el-form-item>
          <el-form-item prop="employee" label="员工" size="small" class="item-inline">
            <el-autocomplete
              v-model="teamRow.employee"
              :fetch-suggestions="querySearchTeam"
              @select="handleSelectTeam"
              placeholder="请输入内容"
              :disabled="isDisabled"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="职位" size="small" prop="roleType">
            <el-select v-model="teamRow.roleType" placeholder="请选择">
              <el-option
                v-for="item in GLOBAL.positionList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="isDirector" label="是否是所长" size="small">
            <el-radio-group v-model="teamRow.isDirector">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="roleIds" label="角色" size="small">
            <el-checkbox-group v-model="teamRow.roleIds">
              <el-checkbox v-for="item in roles" :label="item.roleId"
                           :key="item.roleId">
                {{item.roleName}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        label="操作"
        fixed="right"
        width="120">
        <template slot-scope="scope">
          <el-button
            v-if="!scope.row.state"
            @click.native.prevent="editState(scope.row.userId,1)"
            type="text"
            size="small">
            启用
          </el-button>
          <el-button
            v-else
            @click.native.prevent="editState(scope.row.userId,0)"
            type="text"
            size="small">
            禁用
          </el-button>
          <el-button
            @click.native.prevent="editTeam(scope.row.userId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import { addUser, changeUser, findInfoById, getList, getListRole, getListUser, selectTeam } from '@/api/users'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'

  const state = {
    props: ['colConfig'],
    template: `
  <el-table-column :label="colConfig.label" :min-width="colConfig.minWidth">
      <span slot-scope="scope">
          <span v-if="scope.row[colConfig.prop]" style="color:#67C23A">启用</span>
          <span v-else style="color:#F56C6C" >禁用</span>
      </span>
  </el-table-column>
  `
  }

  const isDirector = function(row, column) {
    return row.isDirector ? '是' : '否'
  }
  const teamName = function(row, column) {
    return row.employees.teamName
  }
  const name = function(row, column) {
    return row.employees.name
  }
  const position = function(row, column) {
    return row.employees.position
  }
  const idNumber = function(row, column) {
    return row.employees.idNumber
  }
  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'userName', label: '登录账户', minWidth: '10%', fixed: true },
          { prop: 'teamName', label: '所属团队', minWidth: '10%', formatter: teamName },
          { prop: 'name', label: '员工', minWidth: '10%', formatter: name },
          { prop: 'position', label: '职位', minWidth: '10%', formatter: position },
          { prop: 'isDirector', label: '是否是所长', minWidth: '10%', formatter: isDirector },
          { prop: 'idNumber', label: '身份证', minWidth: '25%', formatter: idNumber },
          { prop: 'state', label: '状态', minWidth: '10%', component: state },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        teams: [],
        roles: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增登录账户',
        dialogType: 0,
        teamRow: {
          roleIds: [],
          isDirector: 0
        },
        roleIds: '',
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        pca: pca,
        message: '',
        rules: {
          userName: [
            { required: true, message: '请输入登录账户', trigger: 'change' }
          ],
          employee: [
            { required: true, message: '请选择员工', trigger: 'change' }
          ],
          roleType: [
            { required: true, message: '请选择职位', trigger: 'change' }
          ],
          isDirector: [
            { required: true, message: '请选择是否是所长', trigger: 'change' }
          ],
          roleIds: [
            { required: true, message: '请选择角色', trigger: 'change' }
          ]
        },
        visible: false,
        isDisabled: false
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
      this.selectTeam()
      this.getListRole()
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getListUser(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          console.log(this.tableData)
          this.listLoading = false
        })
      },
      selectTeam() {
        selectTeam().then(response => {
          this.teams = response.responseBody
        })
      },
      getListRole() {
        getListRole().then(response => {
          this.roles = response.responseBody
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.isDisabled = false
        this.dialogTitle = '新增登录账户'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
      },
      editTeam(userId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.isDisabled = true
        this.dialogTitle = '修改登录账户'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 0
        const params = {
          userId: userId
        }
        findInfoById(params).then(response => {
          const data = response.responseBody
          this.teamRow = Object.assign({}, this.teamRow, data)
          const roleIds = data.roleIds.split(',')
          this.teamRow.roleIds = []
          roleIds.forEach(value => {
            this.teamRow.roleIds.push(parseInt(value))
          })
          console.log(this.teamRow.roleIds)
          this.teamRow.employee = data.name + ' ' + data.idNumber
          this.roleIds = data.roleIds.split(',')
        })
      },
      submitForm(formName) {
        const params = new FormData()
        params.append('userName', this.teamRow.userName)
        params.append('employeeId', this.teamRow.employeeId)
        params.append('roleType', this.teamRow.roleType)
        params.append('roleIds', this.teamRow.roleIds.join(','))
        params.append('isDirector', this.teamRow.isDirector)
        if (!this.dialogType) {
          params.append('userId', this.teamRow.userId)
          params.append('isChangeRole', this.teamRow.roleIds.join(',') === this.roleIds ? 0 : 1)
        }
        if (this.teamRow.employeeId) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addUser(params).then(response => {
                  this.outerVisible = false
                  this.fetchData()
                })
              } else {
                changeUser(params).then(response => {
                  this.outerVisible = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message({
            message: '该员工不存在',
            type: 'warning'
          })
        }
      },
      editState(userId, state) {
        const params = new FormData()
        params.append('userId', userId)
        params.append('state', state)
        changeUser(params).then(response => {
          this.outerVisible = false
          this.fetchData()
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = new FormData()
        params.append('userId', scope.row.userId)
        params.append('isDel', 1)
        changeUser(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = this.teamRow.addressId[0]
        this.teamRow.cityId = this.teamRow.addressId[1]
        this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.employeeId
        const params = {
          keyword: queryString
        }
        getList(params).then(response => {
          for (const i of response.responseBody) {
            i.value = i.name + ' ' + i.idNumber
          }
          let nameList = response.responseBody
          if (nameList.length === 0) {
            nameList = [{ value: '暂无数据' }]
          }
          callback(nameList)
        })
      },
      handleSelectTeam(item) {
        this.teamRow.employeeId = item.employeeId
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
